package com.zzx.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzx.domain.ChatHistory;
import com.zzx.mapper.ChatHistoryMapper;
import com.zzx.service.ChatHistoryService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ChatHistoryServiceImpl extends ServiceImpl<ChatHistoryMapper, ChatHistory> implements ChatHistoryService {
    @Override
    public List<String> getChatIds(String type, Long userId) {
        //select * from chatHistory where type = ? and userId = ?
        List<ChatHistory> chatHistoryList = lambdaQuery()
                .eq(ChatHistory::getType, type)
                .eq(userId != null, ChatHistory::getUserId, userId)
                .orderByDesc(ChatHistory::getCreateTime)
                .list();
        List<String> idsList = chatHistoryList.stream().map(list1 -> {
            String conversationId = list1.getConversationId();
            return conversationId;
        }).toList();
        return idsList;
    }

    @Override
    public void saveChatHistory(String type, String chatId) {
        //保存之前先查数据库中有没有对应id的数据,没有了再保存,做幂等
        Long count = lambdaQuery()
                .eq(ChatHistory::getType, type)
                .eq(ChatHistory::getConversationId, chatId)
                .count();
        if (count != null && count > 0) {
            return;
        }
        ChatHistory chatHistory = ChatHistory.builder()
                .conversationId(chatId)
                .title(type + chatId)
                .userId(null)
                .createTime(LocalDateTime.now())
                .type(type)
                .build();
        save(chatHistory);
    }
}
